package com.example.administrator.liveapp.fragment;

import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.activity.ArticleDetailsPage;
import com.example.administrator.liveapp.activity.ArticlePage;
import com.example.administrator.liveapp.activity.BookingDetailsPage;
import com.example.administrator.liveapp.activity.LiveDetailsPage;
import com.example.administrator.liveapp.activity.LiveListPage;
import com.example.administrator.liveapp.activity.LoginPage;
import com.example.administrator.liveapp.activity.MallDetailsPage;
import com.example.administrator.liveapp.activity.WxLoginPage;
import com.example.administrator.liveapp.adapter.FoundFragmentAdapter;
import com.example.administrator.liveapp.base.BaseFragment;
import com.example.administrator.liveapp.bean.FoundBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.GlideImageLoader;

import com.example.administrator.liveapp.view.FullyLinearLayoutManager;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 以前首页Fragment(已经没有用了)
 */
public class FoundFragment extends BaseFragment {
    /**
     * 标题栏布局
     */
    private RelativeLayout title_bar;
    /**
     * 标题栏标题
     */
    private TextView title_bar_text;

    private View view;
    private String[] cateid;//区分轮播图跳转页面
    private String[] id;//轮播图对应的跳转页面id
    private List<String> images;
    private List<String> titles;
    private Banner banner;
    private RecyclerView found_recycler_view;
    private FullyLinearLayoutManager mLinearLayoutManager;
    private FoundFragmentAdapter foundFragmentAdapter;
    private RadioButton article_more;
    private RadioButton live_more;
    private ImageView homePage_liveImage, homePage_liveImage2,found_playstatic,found_playstatic2;
    private TextView title2, title;
    private RadioButton home_watch2, home_watch, home_thumb2, home_thumb;
    private RoundedImageView found_shopping;
    private TextView shopping_title;
    private TextView announcement_textview;//公告
    private TextView trailer_textview;//预告
    private FoundBean bean;
    /**
     * 下拉刷新
     */
    private RefreshLayout mRefreshLayout;
    private static boolean isFirstEnter = true;
    private View loadView;//loding页面（加载页）
    private String activityId, activityId2;


    @Override
    protected View initView() {
        view = View.inflate(mContext, R.layout.foundfragment_layout, null);
        title_bar = (RelativeLayout) view.findViewById(R.id.title_bar);
        title_bar_text = (TextView) view.findViewById(R.id.title_bar_text);
        loadView = view.findViewById(R.id.loadViews);
        banner = (Banner) view.findViewById(R.id.banner);
        found_recycler_view = (RecyclerView) view.findViewById(R.id.found_recycler_view);
        article_more = (RadioButton) view.findViewById(R.id.article_more);
        live_more = (RadioButton) view.findViewById(R.id.live_more);
        homePage_liveImage = (ImageView) view.findViewById(R.id.homePage_liveImage);
        homePage_liveImage2 = (ImageView) view.findViewById(R.id.homePage_liveImage2);
        found_playstatic = (ImageView) view.findViewById(R.id.found_playstatic);
        found_playstatic2 = (ImageView) view.findViewById(R.id.found_playstatic2);
        title = (TextView) view.findViewById(R.id.title);
        title2 = (TextView) view.findViewById(R.id.title2);
        home_watch = (RadioButton) view.findViewById(R.id.home_watch);
        home_watch2 = (RadioButton) view.findViewById(R.id.home_watch2);
        home_thumb = (RadioButton) view.findViewById(R.id.home_thumb);
        home_thumb2 = (RadioButton) view.findViewById(R.id.home_thumb2);
        found_shopping = (RoundedImageView) view.findViewById(R.id.found_shopping);
        shopping_title = (TextView) view.findViewById(R.id.shopping_title);
        announcement_textview = (TextView) view.findViewById(R.id.announcement_textview);
        trailer_textview = (TextView) view.findViewById(R.id.trailer_textview);
        /**
         * 下拉刷新
         */
        mRefreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);
        setThemeColor(R.color.colorPrimary);
        if (isFirstEnter) {
            initData();
            isFirstEnter = false;
//            mRefreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
        }
        return view;
    }

    private void setThemeColor(int colorPrimary) {
        mRefreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.holo_blue_dark);
        //改变手机状态栏背景色
//        if (Build.VERSION.SDK_INT >= 21) {
//            getActivity().getWindow().setStatusBarColor(ContextCompat.getColor(getActivity(), colorPrimaryDark));
//        }
    }

    private void articleListener() {
        article_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ApplicationUtils.getInstance().loginBean == null) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), WxLoginPage.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                intent.setClass(getContext(), ArticlePage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
        live_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ApplicationUtils.getInstance().loginBean == null) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), WxLoginPage.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                intent.setClass(getContext(), LiveListPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
        homePage_liveImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ApplicationUtils.getInstance().loginBean == null) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), WxLoginPage.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("playstatics",bean.getVideo().get(0).getPlaystatics());
                intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                intent.putExtra("videoId", bean.getVideo().get(0).getVideoid());
                intent.setClass(getContext(), LiveDetailsPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
        homePage_liveImage2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ApplicationUtils.getInstance().loginBean == null) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), WxLoginPage.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("playstatics",bean.getVideo().get(1).getPlaystatics());
                intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                intent.putExtra("videoId", bean.getVideo().get(1).getVideoid());
                intent.setClass(getContext(), LiveDetailsPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
        announcement_textview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ApplicationUtils.getInstance().loginBean == null) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), WxLoginPage.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("timeStatus", bean.getActivity().get(0).getTimeStatus() + "");
                intent.putExtra("activityId", activityId);
                intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                intent.setClass(mContext, BookingDetailsPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
        trailer_textview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ApplicationUtils.getInstance().loginBean == null) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), WxLoginPage.class);
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("timeStatus", bean.getActivity().get(1).getTimeStatus() + "");
                intent.putExtra("activityId", activityId2);
                intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                intent.setClass(mContext, BookingDetailsPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);

            }
        });
        mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //底部加载
            }

            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                //下拉刷新
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                        refreshlayout.finishRefresh();
                    }
                }, 2000);
            }
        });
        found_shopping.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("bookId", bean.getBook().get(0).getBookid());
                intent.setClass(mContext, MallDetailsPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
    }


    @Override
    protected void initData() {
        super.initData();
        //首页数据源
        String urls = AppUrl.URL + AppUrl.HomePageURL;
        XUtils.Get(urls, null, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                bean = gson.fromJson(result, FoundBean.class);
                if (bean.getActivity().get(0).getActivitytitle() != null && bean.getActivity().get(1).getActivitytitle() != null) {
                    announcement_textview.setText(bean.getActivity().get(0).getActivitytitle());//设置公告内容
                    activityId = bean.getActivity().get(0).getActivityid();
                    trailer_textview.setText(bean.getActivity().get(1).getActivitytitle());//设置预告内容
                    activityId2 = bean.getActivity().get(1).getActivityid();
                }
                if (bean.getVideo().get(0).getVideotitle() != null & bean.getVideo().get(1).getVideotitle() != null) {
                    title.setText(bean.getVideo().get(0).getVideotitle());
                    title2.setText(bean.getVideo().get(1).getVideotitle());
                    if (bean.getVideo().get(0).getVideoimgurl() != null) {
                        Glide.with(getActivity()).load(AppUrl.URL + (bean.getVideo().get(0).getVideoimgurl()).substring(1, (bean.getVideo().get(0).getVideoimgurl()).indexOf("|"))).into(homePage_liveImage);
                    }
                    if (bean.getVideo().get(1).getVideoimgurl() != null) {
                        Glide.with(getActivity()).load(AppUrl.URL + (bean.getVideo().get(1).getVideoimgurl()).substring(1, (bean.getVideo().get(1).getVideoimgurl()).indexOf("|"))).into(homePage_liveImage2);
                    }
                    if(bean.getVideo().get(0).getPlaystatics().equals("0")){
                        found_playstatic.setImageResource(R.drawable.zhibozhong);
                    }else if(bean.getVideo().get(0).getPlaystatics().equals("1")){
                        found_playstatic.setImageResource(R.drawable.huifang);
                    }else if(bean.getVideo().get(0).getPlaystatics().equals("1")){
                        found_playstatic.setImageResource(R.drawable.yugao);
                    }
                    if(bean.getVideo().get(1).getPlaystatics().equals("0")){
                        found_playstatic2.setImageResource(R.drawable.zhibozhong);
                    }else if(bean.getVideo().get(1).getPlaystatics().equals("1")){
                        found_playstatic2.setImageResource(R.drawable.huifang);
                    }else if(bean.getVideo().get(1).getPlaystatics().equals("1")){
                        found_playstatic2.setImageResource(R.drawable.yugao);
                    }
                    home_watch.setText(bean.getVideo().get(0).getLikecount());
                    home_watch2.setText(bean.getVideo().get(1).getLikecount());
                    home_thumb.setText(bean.getVideo().get(0).getVideoviewcount());
                    home_thumb2.setText(bean.getVideo().get(1).getVideoviewcount());
                }
                if (bean.getBook().get(0).getBookbannerimg() != null && bean.getBook().get(0).getBooktitle() != null) {
                    shopping_title.setText(bean.getBook().get(0).getBooktitle());
                    Glide.with(getActivity()).load(AppUrl.URL + (bean.getBook().get(0).getBookbannerimg()).substring(1, (bean.getBook().get(0).getBookbannerimg()).indexOf("|"))).into(found_shopping);
                }
                cateid = new String[bean.getBanner().size()];
                id = new String[bean.getBanner().size()];
                images = new ArrayList<>();
                titles = new ArrayList<>();
                if (bean.getBanner() != null) {
                    for (int i = 0; i < bean.getBanner().size(); i++) {
                        //ViewPager数据源
                        String imageUrl = (bean.getBanner().get(i).getImgurl());
                        cateid[i] = bean.getBanner().get(i).getCateid();
                        id[i] = bean.getBanner().get(i).getTypeid();
                        images.add(AppUrl.URL + imageUrl.substring(1, imageUrl.indexOf("|")));
                        titles.add(bean.getBanner().get(i).getBannertitle());
                    }
                    recyclerView();
                    banner();
                    /**
                     * 标题栏
                     */
                    title_bar.setVisibility(View.VISIBLE);
                    title_bar_text.setText("首页");
                    loadView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Toast.makeText(getContext(),bean.getMessage()+"网络请求失败",Toast.LENGTH_SHORT).show();
            }
        });
        articleListener();
    }

    private void recyclerView() {
        //创建默认的LinearLayoutManager
        mLinearLayoutManager = new FullyLinearLayoutManager(mContext);
        mLinearLayoutManager.setScrollEnabled(false);
        found_recycler_view.setLayoutManager(mLinearLayoutManager);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        found_recycler_view.setHasFixedSize(true);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //创建并设置Adapter
        foundFragmentAdapter = new FoundFragmentAdapter(bean.getArticle());
        found_recycler_view.setAdapter(foundFragmentAdapter);
        foundFragmentAdapter.setOnItemClickListener(new FoundFragmentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("articleId", bean.getArticle().get(position).getArticleid());
                if (ApplicationUtils.getInstance().loginBean != null) {
                    intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                } else {
                    intent.putExtra("consumerId", "");
                }
                intent.setClass(mContext, ArticleDetailsPage.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
            }
        });
    }

    /**
     * 顶部ViewPager样式设置
     */
    public void banner() {
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(images);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(4000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        //解决banner(ViewPage)和swipeRefreshLayout(下拉刷新的冲突事件)
        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                enableDisableSwipeRefresh(state == ViewPager.SCROLL_STATE_IDLE);
            }

        });
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent();
                switch (position) {
                    case 0:
                        if (ApplicationUtils.getInstance().loginBean == null) {
                            Intent intent2 = new Intent();
                            intent2.setClass(getContext(), WxLoginPage.class);
                            startActivity(intent2);
                            getActivity().overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                            return;
                        }
                        intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                        intent.putExtra("activityId", id[0]);
                        intent.putExtra("timeStatus", bean.getBanner().get(0).getTimeStatus() + "");
                        intent.setClass(getActivity(), BookingDetailsPage.class);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        break;
                    case 1:
                        intent.setClass(getActivity(), MallDetailsPage.class);
                        intent.putExtra("bookId", id[1]);
                        if (ApplicationUtils.getInstance().loginBean != null) {
                            intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                        } else {
                            intent.putExtra("consumerId", "");
                        }
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        break;
                    case 2:
                        intent.putExtra("articleId", id[2]);
                        if (ApplicationUtils.getInstance().loginBean != null) {
                            intent.putExtra("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                        } else {
                            intent.putExtra("consumerId", "");
                        }
                        intent.setClass(getActivity(), ArticleDetailsPage.class);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        break;
                }
            }
        });
    }

    protected void enableDisableSwipeRefresh(boolean enable) {
        if (mRefreshLayout != null) {
//            setEnabled(enable)
            mRefreshLayout.setEnableRefresh(enable);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

}
